<template>
	<view class="login-container">
		<uni-icons type="contact" size="120" class="contactIcon"></uni-icons>
		<view class="logintext">
			登录享更多权益
		</view>
		<!-- open-type="getUserInfo"是固定写法， @getuserinfo是button的属性，详见https://uniapp.dcloud.io/component/button 和https://uniapp.dcloud.io/api/other/authorize?id=authorize-->
		<button type="primary"  open-type="getUserProfile" class="login-btn"  @click="getuInfo">一键登录</button>
		<image src="../../static/login1.gif" mode="widthFix"></image>
	</view>
</template>

<script>
	import {mapState,mapMutations} from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				query:{}
			};
		},
		methods:{
			...mapMutations('m_user',['updataUserInfo','updataToken','updataRedirectInfo']),
			// 点击登录 获取用户信息
			getuInfo(){
				 uni.getUserProfile({
				        desc:'登录',
				        success:(res)=>{
					     // console.log(res);
						 this.updataUserInfo(res.userInfo);
						
						 // 调用方法获取token
						 this.getTokenData(res);
						 
						 console.log('this.redirectInfo',this.redirectInfo)
						 // 返回之前的页面
						 if(this.redirectInfo.openType==='switchTab'){
							 uni.switchTab({
								url:this.redirectInfo.from,
								
							 })
						 }
						 // 清空vuex中重定向
						this.updataRedirectInfo(null)
						
						 
					},
					fail:(err)=>{
					     console.log(err);
						 uni.$showMsg('您取消了授权')
				        }
				    })
			},
			
			// 获取token需要的参数
			async getTokenData(info){
				let that = this
				await uni.login({
					provider: 'weixin',
					success: function (loginRes) {
					    console.log('loginRes',loginRes);
						// 准备参数对象
						that.query = {
							code:loginRes.code,
							rawData:info.rawData,
							iv:info.iv,
							signature:info.signature,
							encryptedData:info.encryptedData
						}
						that.getToken(that.query);
					  },
					fail() {
						uni.$showMsg('登录失败')
					}
				})
			},
			// 搞到token
			async getToken(query){
				// 接口有问题-----无法返回token，只能自定义token
				// const { data: loginResult } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				let token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo"
				this.updataToken(token);
			}
			
			
		},
		computed:{
			...mapState('m_user',['userInfo','redirectInfo'])
		}
	}
</script>

<style lang="scss">
.login-container{
	display: flex;
	height: 100vh;
	flex-direction: column;
	align-items: center;
	.contactIcon{
		margin-top: 150rpx;
	}
	.login-btn{
		width: 80%;
		height: 100rpx;
		line-height: 100rpx;
		margin-top: 100rpx;
		margin-bottom: 50rpx;
		color: #FFFFFF;
		text-align: center;
		font-size: 48rpx;
		background-color: #4cc6aa;
		border-radius: 60rpx;
	}
	image{
		width: 100%;
		position: absolute;
		bottom: 0;
		left: 0;
	}
}
</style>
